package org.wwx.protocol;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.wwx.common.Invocation;
import org.wwx.register.LocalRegister;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @date 2025/6/5
 * @author王闻薪
 */
public class HttpServerHandle {

    public void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            final Invocation invocation = (Invocation)new ObjectInputStream(req.getInputStream()).readObject();
            final String interfaceName = invocation.getInterfaceName();
            final Class classImpl = LocalRegister.get(interfaceName);

            final Method method = classImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            final String result = (String)method.invoke(classImpl.newInstance(), invocation.getParameters());

            IOUtils.write(result, resp.getOutputStream());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
}
